package com.wallezhou.upload.servlet;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;

/**
 * 文件分块上传
 */
public class FileUploadServlet extends HttpServlet {
    //数据上传的目录路径参数名
    public static String TARGETDIR = "targetDir";

    //数据上传的目录
    protected String targetDir;

    protected String getConfigParam(String key) {
        return getServletConfig().getInitParameter(key);
    }

    @Override
    public void init() {
        String targetDir = getConfigParam(TARGETDIR);
        if (targetDir != null) {
            this.targetDir = targetDir;
        }else{
            throw new IllegalArgumentException(TARGETDIR+"为FileMergeServelet的必要参数");
        }
    }

    @Override
    protected void service(HttpServletRequest servletRequest, HttpServletResponse servletResponse) throws IOException, ServletException {
        String method = servletRequest.getMethod();
        if (method.equals("OPTIONS")){
            this.doOptions(servletRequest, servletResponse);
            return;
        }
        //需要获取传入的三个参数 file: 文件分块  index: 分块索引值 hash: 文件哈希值(完整文件的hash)
        InputStream is = servletRequest.getPart("file").getInputStream();
        int index = Integer.parseInt(servletRequest.getParameter("index"));
        String hash = servletRequest.getParameter("hash");

        File HASHDIR = new File(this.targetDir+File.separator+hash);
        if(!HASHDIR.exists()) HASHDIR.mkdir();
        File chunkFile = new File(HASHDIR.getAbsolutePath() + File.separator+ hash + "-"+ index);
        if(chunkFile.exists()) return;
        FileOutputStream fos = new FileOutputStream(chunkFile);
        byte[] b = new byte[1024];
        int length;
        while((length= is.read(b))>0){
            fos.write(b,0,length);
        }
        fos.close();
        is.close();
    }

}
